package com.shujia.scala

import scala.io.Source

object Demo30Top10 {
  def main(args: Array[String]): Unit = {
    //2、统计偏科最严重的前十个学生

    //读取分数表
    val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList

    //读取科目表
    val subjects: List[String] = Source.fromFile("data/subject.txt").getLines().toList

    //将科目表转换成字典
    val idAndMaxScore: Map[String, Double] = subjects
      .map(line => {
        val split: Array[String] = line.split(",")
        val cId: String = split.head
        val maxScore: Double = split.last.toDouble
        (cId, maxScore)
      }).toMap

    //解析分数表
    val oneScores: List[(String, Double)] = scores.map(line => {
      val split: Array[String] = line.split(",")
      val id: String = split(0)
      val cId: String = split(1)
      val score: Double = split(2).toDouble
      //通过科目编号获取科目总分
      val maxScore: Double = idAndMaxScore.getOrElse(cId, 0)

      //归一化
      val oneScore: Double = score / maxScore * 100

      (id, oneScore)
    })


    //按照学号分组
    val groupBy: Map[String, List[(String, Double)]] = oneScores.groupBy(kv => kv._1)

    //计算方差
    val stds: Map[String, Double] = groupBy.mapValues(value => {
      val score: List[Double] = value.map(kv => kv._2)
      //计算平均值
      val avg: Double = score.sum / score.length
      //计算差值的平方和
      val std: Double = score.map(sco => (sco - avg) * (sco - avg)).sum / score.length
      std
    })

    //排序取前十
    val top10: List[(String, Double)] = stds.toList.sortBy(kv => -kv._2).take(10)

    top10.foreach(println)

  }
}
